//
//  DownloadImgViewController.swift
//  downloadImage
//
//  Created by Galaxy on 2022/6/22.
//  下载图片

import UIKit
import WCDBSwift
import Photos

class DownloadImgViewController: UIViewController {

    @objc private dynamic var logContent:String = ""
    private var isDownloading:Bool = false
    var timer:DispatchSourceTimer?
    
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        timer?.cancel()
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
        view.backgroundColor = .systemBackground
        makeUI()
        // 定时器更新文字
        timer = DispatchSource.makeTimerSource(flags: .strict, queue: DispatchQueue.global())
        timer?.schedule(deadline: .now(), repeating: .seconds(1))
        timer?.setEventHandler {
            DispatchQueue.main.async {
                self.textView.text = self.logContent
                self.textView.scrollRangeToVisible(NSRange(location: self.logContent.count, length: 1))
            }
        }
        timer?.resume()
    }
    
    func makeUI() {
        let bottomBtn = UIButton.init(type: .custom)
        view.addSubview(bottomBtn)
        bottomBtn.snp.makeConstraints { make in
            make.centerX.equalToSuperview()
            make.size.equalTo(CGSize(width: 100, height: 40))
            make.bottom.equalTo(view.safeAreaLayoutGuide.snp.bottom).offset(-10)
        }
        bottomBtn.backgroundColor = .red
        bottomBtn.setTitle("开始", for: .normal)
        bottomBtn.setTitle("暂停", for: .selected)
        bottomBtn.isSelected = false
        bottomBtn.reactive.controlEvents(.touchUpInside).observeValues { button in
            if bottomBtn.isSelected == false {
                // 开始
                self.downloadImg()
            }else{
                // 暂停
                _ = LogTool.init().saveLog(logContent: self.logContent)
            }
            bottomBtn.isSelected = !bottomBtn.isSelected
            self.isDownloading = !self.isDownloading
        }
    }
    
    lazy var textView: UITextView = {
        let textView = UITextView.init()
        view.addSubview(textView)
        textView.snp.makeConstraints { make in
            make.left.right.equalToSuperview()
            make.bottom.equalTo(view.safeAreaLayoutGuide.snp.bottom).offset(-60)
            make.top.equalTo(view.safeAreaLayoutGuide.snp.top)
        }
        textView.backgroundColor = .black
        textView.textColor = .white
        textView.isEditable = false
        textView.layoutManager.allowsNonContiguousLayout = false
        return textView
    }()
    
    func downloadImg() {
        // TODO: 从数据库中获取一条未下载的图片
        let model:ImageModel? = try! FileTool().getDb().getObject(fromTable: "image", where: ImageModel.Properties.didDownload == false)
        if model == nil {
            self.logContent += "图片下载完毕"
            self.isDownloading = false
            return
        }
        print(model!.imgUrl!)
        self.logContent += "\n开始下载图片\(model!.imgUrl ?? "")"
        let urlFileName = model!.imgUrl!.split(separator: "/").last!
        let fileName = String(urlFileName)
        let savePath = FileTool.init().getDocumentPath()+"/"+fileName;
        print("保存位置是"+savePath)
        QYRequestData.shared.downloadFile(urlStr: model!.imgUrl!, savePath: savePath) { progress in
            print("总数据\(progress.totalUnitCount)，已下载\(progress.completedUnitCount),下载进度\(progress.fractionCompleted*100)%")
        } success: {
            print("图片下载成功，开始保存")
            self.logContent += "\n图片下载成功，开始保存"
            let image = UIImage.init(contentsOfFile: savePath)
            if image != nil {
                PHPhotoLibrary.shared().performChanges {
                    PHAssetChangeRequest.creationRequestForAsset(from: image!)
                }completionHandler: { Bool, error in
                    DispatchQueue.main.async {
                        if error != nil {
                            print("图片保存失败\(String(describing: error?.localizedDescription))")
                            self.logContent += "\n图片保存失败"
                            let alert = UIAlertController.init(title: "提示", message: "图片保存失败", preferredStyle: .alert)
                            let deleteAction = UIAlertAction.init(title: "删除", style: .default) { action in
                                try! FileTool().getDb().delete(fromTable: "image", where: ImageModel.Properties.identifier == model!.identifier!)
                            }
                            alert.addAction(deleteAction)
                            let cancelAction = UIAlertAction.init(title: "取消", style: .cancel)
                            alert.addAction(cancelAction)
                            self.present(alert, animated: true)
                        }else{
                            // 修改model下载状态为已下载
                            model!.didDownload = true
                            try! FileTool().getDb().update(table: "image", on: ImageModel.Properties.didDownload, with: model!, where: ImageModel.Properties.identifier == model!.identifier!)
                            self.logContent += "\n图片保存成功"
                            _ = FileTool.init().deleteFileWithPath(path: savePath)
                            if self.isDownloading {
                                self.downloadImg()
                            }
                        }
                    }
                }
            } else {
                self.logContent += "\n非正常图片文件，跳过"
                model!.didDownload = true
                try! FileTool().getDb().update(table: "image", on: ImageModel.Properties.didDownload, with: model!, where: ImageModel.Properties.identifier == model!.identifier!)
                if self.isDownloading {
                    self.downloadImg()
                }
            }
        } failure: { error in
            self.logContent += "\n下载失败，程序暂停"
            print("图片下载失败")
            let alert = UIAlertController.init(title: "提示", message: "图片下载失败", preferredStyle: .alert)
            let deleteAction = UIAlertAction.init(title: "删除", style: .default) { action in
                try! FileTool().getDb().delete(fromTable: "image", where: ImageModel.Properties.identifier == model!.identifier!)
            }
            alert.addAction(deleteAction)
            let cancelAction = UIAlertAction.init(title: "取消", style: .cancel)
            alert.addAction(cancelAction)
            self.present(alert, animated: true)
        }
    }
}
